<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="FUsername">
      <el-input v-model="loginForm.FUsername" placeholder="用户名：admin / user">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="FPassword">
      <el-input
        v-model="loginForm.FPassword"
        type="FPassword"
        placeholder="密码：123456"
        show-password
        autocomplete="new-FPassword"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification, ElMessageBox } from "element-plus";
import { loginApi, checkAuthApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  FUsername: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  FPassword: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  FUsername: "",
  FPassword: ""
});

// login
const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1. 先调用 checkAuthApi 检测是否有其他登录
      const { data } = await checkAuthApi({ ...loginForm });
      if (data.isLogin && data.sessionInfo) {
        const confirmed = await ElMessageBox.confirm(
          `该账号已在其他设备登录，是否确认强制登录？\n登录时间：${data.sessionInfo.loginTime}\n设备信息：${data.sessionInfo.device}`,
          "登录确认",
          {
            confirmButtonText: "确认登录",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).catch(() => false); // 若取消返回 false

        if (!confirmed) return;
      }

      // 2. 执行登录接口
      const res = await loginApi({ ...loginForm, FPassword: loginForm.FPassword });
      userStore.setToken(res.data.access_token);
      userStore.setUserInfo(res.data);

      // 3. 添加动态路由
      await initDynamicRouter();

      // 4. 清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 5. 跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: "文档管理系统",
        message: "欢迎登录 BH-Admin",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";
</style>
